package com.example.gastometro;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.SQLException;

public class DbAdapter {

	private SQLiteDatabase database;
	private DbHelper dbHelper;
	private String[] allColumns = { DbHelper.ID, DbHelper.NOME, DbHelper.LOCAL,	DbHelper.VALOR, DbHelper.DATA};
	
	public DbAdapter(Context context) {          
		dbHelper = new DbHelper(context);
		}
	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}
	
	public Gasto createGasto(String nome, String local, String valor, String data) { 
        ContentValues values = new ContentValues(); 
        values.put(dbHelper.NOME, nome); 
        values.put(dbHelper.LOCAL,local); 
        values.put(dbHelper.VALOR,valor); 
        values.put(dbHelper.DATA, data); 
        long insertId = database.insert(dbHelper.TABLE_NAME, null, values); 
       // To show how to query 
       Cursor cursor = database.query(dbHelper.TABLE_NAME, allColumns, dbHelper.ID + " = " + 
       insertId, null,null, null, null); 
       cursor.moveToFirst(); 
       return cursorToGasto(cursor); 
}
	public void EliminaGasto (int idGasto){ 
        database.delete(DbHelper.TABLE_NAME, DbHelper.ID + " = " + idGasto, 
         null); 
}
	
	private Gasto cursorToGasto(Cursor cursor) { 
        
        
        Gasto gasto = new Gasto(cursor.getLong(0),cursor.getString(1),cursor.getString(2),cursor.getString(3), cursor.getString(4)); 
        return gasto; 
}
	public Cursor getGastos(){ 
        Cursor cursor = database.rawQuery("select _id, nome,local,valor,data from gastos2", null); 
        return cursor; 
}
	
	public Gasto getGasto (int idGasto){ 
        Cursor cursor = database.query(dbHelper.TABLE_NAME, allColumns, dbHelper.ID + " = " + idGasto, null,null, null, null); 
        cursor.moveToFirst(); 
        return cursorToGasto(cursor); 
}
	
}
